package megadict.draft.index;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.*;

import org.junit.Test;

public class CharBufferLearning {

    @Test
    public void testUsingCharBuffer() {
        
        File indexFile = new File("C:/test/av.index");
        
        CharBuffer charBuffer = makeCharBuffer(indexFile);        
        
        int offset = 10;
        int length = 100;
        char[] buffer = new char[length];
        
        charBuffer.position(offset);
        charBuffer.get(buffer);
        
        String string = new String(buffer);
        System.out.println(string);        
    }
    
    private CharBuffer makeCharBuffer(File file) {
        try {
            FileInputStream rawStream = new FileInputStream("C:/test/av.index");            
            FileChannel channel = rawStream.getChannel();            
            MappedByteBuffer bytebuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
                        
            Charset unicode = Charset.forName("UTF-8");
            CharsetDecoder decoder = unicode.newDecoder();
            return decoder.decode(bytebuffer);
        } catch (FileNotFoundException fnf) {
            throw new RuntimeException(fnf);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }
    
    
}
